package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.adapter.VIP_ZX_HorizontalListViewAdapter;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.bean.VIP_JiLu;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ActivityManger;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.CommonPopWindow;
import com.jaya.budan.views.HorizontalListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class GeRenTG_Buy_2_Activity extends BaseActivity implements View.OnClickListener, CommonPopWindow.ViewClickListener {

    private RelativeLayout back;
    private String access_token, vip_id;
    private int mtype, position_1;
    private TextView tv_chat_nickname, tv_pop_gerentg_agree, tv_gerentg_buy_2;
    private ImageView iv_pop_gerentg_item;
    private Button btn_gerentg_item_count;
    private CheckBox cb_register2;
    private LinearLayout ll_wx;
    private ArrayList<VIP_JiLu> vip_jiLu;
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gerentg_buy_2);
        Intent intent = getIntent();
        access_token = intent.getStringExtra("access_token");
        mtype = intent.getIntExtra("mtype", 0);
        position_1 = intent.getIntExtra("position", 0);
        vip_jiLu = (ArrayList<VIP_JiLu>) intent.getSerializableExtra("vip_jiLu");
        back = findViewById(R.id.back);
        ll_wx = findViewById(R.id.ll_wx);
        tv_chat_nickname = findViewById(R.id.tv_chat_nickname);
        cb_register2 = findViewById(R.id.cb_register2);
        iv_pop_gerentg_item = findViewById(R.id.iv_pop_gerentg_item);
        tv_pop_gerentg_agree = findViewById(R.id.tv_pop_gerentg_agree);
        tv_gerentg_buy_2 = findViewById(R.id.tv_gerentg_buy_2);
        btn_gerentg_item_count = findViewById(R.id.btn_gerentg_item_count);
        back.setOnClickListener(this);
        ll_wx.setOnClickListener(this);
        if (mtype == 1){
            tv_chat_nickname.setText("购买个人推广");
        } else {
            tv_chat_nickname.setText("购买动态推广");
        }
        HorizontalListView main_hlv_vip = findViewById(R.id.main_hlv_vip);
        // 获取屏幕宽高
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
        VIP_ZX_HorizontalListViewAdapter adapter = new VIP_ZX_HorizontalListViewAdapter(GeRenTG_Buy_2_Activity.this, screenWidth, null, null, 4, vip_jiLu, vip_jiLu.get(position_1).getDetail());
        main_hlv_vip.setAdapter(adapter);
        main_hlv_vip.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                vip_id = vip_jiLu.get(position_1).getDetail().get(position).getId();
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
            }
        });
        btn_gerentg_item_count.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ToolUtils.isEmpty(vip_id)){
                    JSONObject object = new JSONObject();
                    try {
                        object.put("tt_id", vip_id);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    postBuyData(object, v);
                }
            }
        });
        tv_gerentg_buy_2.setText("" + vip_jiLu.get(position_1).getName());
        Glide.with(this).load(vip_jiLu.get(position_1).getIcon()).apply(new RequestOptions()
                .placeholder(R.mipmap.iv_main_item).error(R.mipmap.iv_main_item)
                .diskCacheStrategy(DiskCacheStrategy.NONE)//关闭Glide的硬盘缓存机制
        ).into(iv_pop_gerentg_item);
        SpannableString spanString = new SpannableString("服务协议");
        spanString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //点击的响应事件
                ToolUtils.showToast(GeRenTG_Buy_2_Activity.this, "服务协议");
            }
        }, 0, spanString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        SpannableString spanString2 = new SpannableString("推广要求");
        spanString2.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //点击的响应事件
                ToolUtils.showToast(GeRenTG_Buy_2_Activity.this, "推广要求");
            }
        }, 0, spanString2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanString2.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 0, spanString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_pop_gerentg_agree.setText("已阅读并同意");
        tv_pop_gerentg_agree.append(spanString);
        tv_pop_gerentg_agree.append("和");
        tv_pop_gerentg_agree.append(spanString2);
        tv_pop_gerentg_agree.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_wx:
                cb_register2.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                btn_gerentg_item_count.setEnabled(true);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     */
    private void postBuyData(JSONObject object, View v) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.gr_my_dongtai_Buy_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("xinyun", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        CommonPopWindow.newBuilder()
                                .setView(R.layout.pop_geren_fans_cancle_2)
                                .setAnimationStyle(R.style.AnimUp)
                                .setBackgroundDrawable(new BitmapDrawable())
                                .setSize(0, 600)
                                .setViewOnClickListener(GeRenTG_Buy_2_Activity.this)
                                .setBackgroundDarkEnable(true)
                                .setBackgroundAlpha(0.7f)
                                .build(GeRenTG_Buy_2_Activity.this)
                                .showAsCenter(v);
                    } else if (code == 300){
                        CommonPopWindow.newBuilder()
                                .setView(R.layout.pop_geren_fans_cancle)
                                .setAnimationStyle(R.style.AnimUp)
                                .setBackgroundDrawable(new BitmapDrawable())
                                .setSize(0, 600)
                                .setViewOnClickListener(GeRenTG_Buy_2_Activity.this)
                                .setBackgroundDarkEnable(true)
                                .setBackgroundAlpha(0.7f)
                                .build(GeRenTG_Buy_2_Activity.this)
                                .showAsCenter(v);
                    } else {
                        ToolUtils.showToast(GeRenTG_Buy_2_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(GeRenTG_Buy_2_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.pop_geren_fans_cancle:
                TextView tv_cancle = view.findViewById(R.id.tv_cancle);
                TextView tv_geren_fans_cancle = view.findViewById(R.id.tv_geren_fans_cancle);
                TextView img_guanbi = view.findViewById(R.id.img_guanbi);
                tv_geren_fans_cancle.setText("您的布丁余额不足，请充值后再进行购买");
                tv_cancle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                    }
                });
                img_guanbi.setText("立即充值");
                img_guanbi.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        Intent intent = new Intent(GeRenTG_Buy_2_Activity.this, My_Wallet_Recharge_Activity.class);
                        intent.putExtra("access_token", access_token);
                        startActivity(intent);
                    }
                });
                break;
            case R.layout.pop_geren_fans_cancle_2:
                TextView tv_cancle1 = view.findViewById(R.id.tv_cancle);
                TextView tv_geren_fans_cancle1 = view.findViewById(R.id.tv_geren_fans_cancle);
                TextView img_guanbi1 = view.findViewById(R.id.img_guanbi);
                tv_geren_fans_cancle1.setText("道具购买成功");
                tv_cancle1.setText("稍后使用");
                tv_cancle1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        GeRenTG_Buy_Activity.activity.finish();
                        finish();
                    }
                });
                img_guanbi1.setText("立即使用");
                img_guanbi1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        GeRenTG_Buy_Activity.activity.finish();
                        Intent intent = new Intent(GeRenTG_Buy_2_Activity.this, GeRenTG_Open_Activity.class);
                        intent.putExtra("access_token", access_token);
                        startActivity(intent);
                        finish();//购买成功，关闭该页面
                    }
                });
                break;
            default:
                break;
        }
    }
}
